package com.andy.qhb.game.task;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import com.andy.qhb.game.Global;


/**
 * 异步延时执行
 * 需要调用延迟执行的时候可使用，避免在代码里面直接调用Thread.sleep()方法
 * 
 * @author andylo25 wrote on 2018/6/11.
 */
public class TimerManager {

	static int aps = Runtime.getRuntime().availableProcessors();
	private volatile static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(aps*2);
	
	public static ScheduledFuture<?> schedule(Supplier<?> action, long delay){
		return executorService.schedule(new Runnable() {
			@Override
			public void run() {
				action.get();
			}
		}, delay, TimeUnit.MILLISECONDS);
	}
	
	public static ScheduledFuture<?> schedule(Runnable action, long delay){
		return executorService.schedule(action, delay, TimeUnit.MILLISECONDS);
	}
	
	public static ScheduledFuture<?> scheduleAtFixedRate(Supplier<?> action,long initialDelay, long period ){
		return executorService.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				try {
					action.get();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, initialDelay,period, TimeUnit.MILLISECONDS);
	}
	
	public static ScheduledFuture<?> scheduleWithFixedDelay(Supplier<?> action,long initialDelay, long period ){
		return executorService.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				action.get();
			}
		}, initialDelay,period, TimeUnit.MILLISECONDS);
	}
	
	/**
	 * 每日执行，在离0 点 【seconds】秒时执行
	 * @param action
	 * @param seconds 秒
	 */
	public static void scheduleEveryday(Supplier<?> action,long seconds ){
		long dayMill = 86400*1000;
		long now = System.currentTimeMillis();
		long dayPass = (now % dayMill)+8*3600*1000; // 东8区
		long delay = seconds+dayMill - dayPass;
		scheduleAtFixedRate(action, delay,dayMill);
	}

	public static void init() {
		// 每日执行
		scheduleEveryday(()->{
			// 划转资金
//			CommonUtils.exchangeCoin();
			// 清理过期游戏内存
			Global.clearGames();
			return null;
		},3600*8);
		
	}
	
	
	
	
}
